<template>
  <view class="notification-icon">
    <view class="icon-container" @click="showNotifications">
      <view class="icon">
        <image src="/static/images/notification.png" mode="aspectFit" style="width: 24px; height: 24px;"></image>
      </view>
      <view v-if="unreadCount > 0" class="badge">
        <text class="badge-text">{{ displayCount }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { notificationApi } from '@/utils/api.js';

export default {
  name: 'NotificationIcon',
  data() {
    return {
      unreadCount: 0,
      timer: null
    };
  },
  computed: {
    displayCount() {
      return this.unreadCount > 99 ? '99+' : this.unreadCount;
    }
  },
  created() {
    // 初始加载未读消息数量
    this.getUnreadCount();
    
    // 设置定时器，每分钟检查一次未读消息
    this.timer = setInterval(() => {
      this.getUnreadCount();
    }, 60000); // 60秒
  },
  onShow() {
    this.getUnreadCount();
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  methods: {
    // 获取未读通知数量
    async getUnreadCount() {
      try {
        const res = await notificationApi.getUnreadCount();
        if (res.code === 200 && res.data !== undefined) {
          this.unreadCount = res.data;
        }
      } catch (error) {
        console.error('获取未读通知数量失败:', error);
      }
    },
    
    // 显示通知列表
    showNotifications() {
      uni.navigateTo({
        url: '/pages/notification/notification'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.notification-icon {
  position: relative;
  
  .icon-container {
    position: relative;
    width: 44rpx;
    height: 44rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .icon {
    width: 44rpx;
    height: 44rpx;
    color: #333; /* SVG图标颜色 */
    
    image {
      object-fit: cover;
      width: 100%;
      height: 100%;
    }
  }
  
  .badge {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    background-color: #FF5252;
    border-radius: 16rpx;
    min-width: 32rpx;
    height: 32rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 6rpx;
    
    .badge-text {
      color: #FFFFFF;
      font-size: 20rpx;
      line-height: 20rpx;
    }
  }
}
</style>
